import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import path from 'path'
import pxToViewPort from 'postcss-px-to-viewport'

const host = process.env.TAURI_DEV_HOST

// https://vitejs.dev/config/
export default defineConfig(async () => ({
  plugins: [react()],

  // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
  base: './',
  resolve: {
    alias: {
      '@': '/src',
      '@/assets': '/src/assets',
      '@/components': '/src/components',
      '@/pages': '/src/pages',
      '@/utils': '/src/utils',
      '@/hooks': '/src/hooks',
      '@/store': '/src/store',
      '@/config': '/src/config',
      '@/api': '/src/api',
      '@/router': '/src/router',
      '@/layouts': '/src/layouts',
      '@/styles': '/src/styles',
      '@/types': '/src/types',
      '@/locale': '/src/locale',
      '@/bug-manager': '/src/apps/bug-manager',
    },
  },
  // 1. prevent vite from obscuring rust errors
  clearScreen: false,
  // 2. tauri expects a fixed port, fail if that port is not available
  server: {
    port: 9060,
    strictPort: true,
    host: host || false,
    hmr: host
      ? {
          protocol: 'ws',
          host,
          port: 9061,
        }
      : undefined,
    watch: {
      // 3. tell vite to ignore watching `src-tauri`
      ignored: ['**/src-tauri/**'],
    },
  },
  css: {
    // px 转 vw 适配移动端
    postcss: {
      plugins: [
        pxToViewPort({
          viewportWidth: 375, // (Number) The width of the viewport.
          viewportHeight: 667, // (Number) The height of the viewport.
          unitPrecision: 5, // (Number) The decimal numbers to allow the REM units to grow to.
          viewportUnit: 'vw', // (String) Expected units.
          selectorBlackList: ['.ignore', '.hairlines'], // (Array) The selectors to ignore and leave as px.
          minPixelValue: 1, // (Number) Set the minimum pixel value to replace.
          mediaQuery: false, // (Boolean) Allow px to be converted in media queries.
        }),
      ]
    },
    preprocessorOptions: {
      less: {
        javascriptEnabled: true,
        additionalData: `@import "${path.resolve(__dirname, './src/styles/var.less')}"; @import "${path.resolve(__dirname, './src/styles/global-color.less')}";`,
      }
    }
  },
}))
